<template>
    <AModal v-model="visible" title="导出数据" width="40%" :footer="null">
        <div class="json-container">
            <json-viewer
                ref="copyRef"
                :value="jsonData"
                :expand-depth="5"
                :copyable="{ copyText: '复制' }"
                boxed
                sort
            ></json-viewer>
        </div>
        <ARow style="margin-top: 20px" type="flex" justify="center">
            <AButton type="primary" style="margin-right: 20px" @click="copy"
                >复制数据</AButton
            >
            <AButton type="primary" @click="exportJSONData">导出代码</AButton>
        </ARow>
    </AModal>
</template>
<script>
import FileSaver from "file-saver";
export default {
    name: "ModelData",
    data() {
        return {
            visible: false,
            jsonData: {},
        };
    },
    methods: {
        show(data = {}) {
            this.visible = true;
            this.jsonData = data;
        },
        copy() {
            navigator.clipboard
                .writeText(JSON.stringify(this.jsonData))
                .then(() => {
                    this.$message.success("复制成功");
                });
        },
        exportJSONData() {
            const fields = this.jsonData.map((item) => ({
                key: item.key,
                label: item.label,
                el: item.el,
                attrs: item.attrs,
                rules: item.rules
                    ? [
                          {
                              message: item.rules,
                              trigger: "change",
                              required: true,
                          },
                      ]
                    : [],
                width: item.width,
            }));
            const data = JSON.stringify(fields);
            const blob = new Blob([data], { type: "application/json" });
            FileSaver.saveAs(blob, `表单配置项.json`);
        },
    },
};
</script>

<style lang="less" scoped>
.json-container {
    min-height: 300px;
    max-height: 500px;
    overflow-y: auto;
}
</style>
